<template>
	<view class="storeBox">
		<view class="topMenu">
			<view class="check tit-txt">
				<view class="">订单</view>
				<view class="hr"></view>
			</view>
			<view class="tit-txt" @click="goToPage('afterSales')">
				<view class="">售后订单</view>
				<view class="hr"></view>
			</view>
			<view class="bluetooth">
				<view class="is-connected changeMerchant" @click="showChangeMerchant"
					v-if="myInfo.id=='1608912445638709250'">切换商户端</view>
				<view class="is-connected changeMerchant" @click="goBack"
					v-if="myInfo.id!='1608912445638709250'&&isBigestAuth">返回</view>
				<!-- <view class='print-set' @click="showPrintSetBox">打印设置</view> -->
				<view @click="showBluetoothBox" v-show="!connectedPriter">未连接打印机</view>
				<view class="is-connected" @click="showBluetoothBox" v-show="connectedPriter">已连接打印机</view>
			</view>
		</view>
		<view class="warn">营业时间：{{ businessHoursStr }}</view>
		<!-- 二期需求 -->
		<view class="tabsContent">
			<u-tabs :list="companyList" name="companyShortName" :is-scroll="false" :current="current"
				@change="tabsChange" font-size="30" :bold="false" active-color="#f5914f" :active-item-style="{
					color: '#f5914f',
					fontSize: '34rpx'
				}"></u-tabs>
		</view>
		<!-- 二期需求 -->
		<!-- <view class="" @click="_setPrintData">接口参数测试</view> -->
		<view class="notice">
			<image src="https://www.yongshantuan.cn/images/yongshan/platformSide/laba.png" mode=""></image>
			<view class="" style='color:red'>{{ storeInfo.merchantAnnouncement }}</view>
		</view>
		<view class="menuContent">
			<view class="menuList menuTop">
				<view class="">菜单列表</view>
				<view class="">当前单量</view>
			</view>
			<view class="menuList" v-for="(item, index) in hcOrderDetailedInfo.list" :key="index">
				<view class="">
					{{ item.tradeName }}
					<text v-if="item.specifications">({{ item.specifications }})</text>
				</view>
				<view class="">{{ item.commodityQuantity }}份</view>
			</view>
			<view class="total">
				总订单量:
				<text>{{ hcOrderDetailedInfo.orderTotal }}份</text>
			</view>
		</view>
		<view class="storeState">
			<view class="tit-new">
				<text class='cczz'>
					出餐状态：{{ statusMap[storeInfo.storeStatus].status }}
				</text>
				<view class='t-btn'>
					<!-- <view :class="statusMap[storeInfo.storeStatus].clsName" class='status' @click="changeStoreState()">
						{{ statusMap[storeInfo.storeStatus].btnName }}
					</view> -->
					<view class="state">
						<view class="">
							<Print ref="print" @getCheckedList='getCheckedList' @checkOverTime="checkOverTime"
								@setPrintData="_setPrintData"></Print>
						</view>
						<!-- <view class="" @click="handleExportXls">
							<view class="">导出</view>
							<view class="num">{{ storeInfo.notExportedCount }}</view>
						</view> -->
					</view>
				</view>
			</view>

			<view class="bloos"></view>
		</view>
		<view class="orderContent">
			<view class='buttonBox'>
				<!-- <view class="allCheck" @click="changeAllCheck">
					<checkbox value="index" :checked="allChecked" class="or-cb" />
					<view class="">全选</view>
				</view> -->
				<view class='time-range'>
					<checkbox :checked="timeRangeChecked" @click='clickTimeRangeChecked' class="or-cb" />
					<view>
						<text @click='clickTimeRangeChecked'>付款时间：</text>
						<text class='cur-time-val' @click='rangeStart.show = true'>
							{{ rangeStart.time }} - {{ rangeEnd.time }}
						</text>
					</view>

					<u-select v-model="rangeStart.show" mode='mutil-column' title='开始时间' confirm-text='下一步'
						:mask-close-able='false' :default-value='rangeStart.default' :list="rangeStart.list"
						@confirm="confirmStartTime">
					</u-select>
					<u-select v-model="rangeEnd.show" mode='mutil-column' title='截止时间' cancel-text='上一步'
						:mask-close-able='false' :default-value='rangeEnd.default' :list="rangeEnd.list"
						@cancel="backToStart" @confirm="confirmEndTime">
					</u-select>
				</view>
			</view>
			<view class="tableBox" v-if="orderList.length != 0">
				<view class="table" :style="{ width: trWidthTotal + 'rpx' }">
					<view class="tr">
						<view class="td"></view>
						<view class="td" :style="{ width: trWidthArr[0] + 'rpx' }">地址</view>
						<view class="td" :style="{ width: trWidthArr[1] + 'rpx' }">序号</view>
						<view class="td" :style="{ width: trWidthArr[2] + 'rpx' }">姓名</view>
						<view class="td sort-col" :class="{ isSort: app.globalData.orderSortType == 'default' }"
							:style="{ width: trWidthArr[3] + 'rpx' }" @click="changeSortBy('default')">菜品</view>
						<view class="td" :style="{ width: trWidthArr[4] + 'rpx' }">备注</view>
						<view class="td sort-col" :class="{ isSort: app.globalData.orderSortType == 'createTime' }"
							@click="changeSortBy('createTime')">{{ this.current === 0 ? '付款时间' : '下单时间' }}</view>
					</view>
					<view class="tr" v-for="(item, index) in orderList" :key="item.pickingSerialNo"
						:class="{ multipleOrders: item.multipleOrders }">
						<view class="td" @click="changeRadioState(index)">
							<checkbox :checked="item.checked" class="or-cb" />
						</view>
						<view class="td" :style="{ width: trWidthArr[0] + 'rpx' }">{{ item.supplyAddress }}</view>
						<view class="td" :style="{ width: trWidthArr[1] + 'rpx' }">{{ item.pickingSerialNo }}</view>
						<view class="td" :style="{ width: trWidthArr[2] + 'rpx' }">{{ item.nameTakingMeal }}</view>
						<view class="td" :style="{ width: trWidthArr[3] + 'rpx' }" v-if='item.nameDishes_red'>
							<text v-for='(tt, idx) in item.nameDishes_red.list' :key="idx"
								:style="{ color: item.nameDishes_red.indexs.includes(idx) ? 'red' : '#000' }">
								{{ (idx > 0 ? '+' : '') + tt }}
							</text>
						</view>
						<view class="td" :style="{ width: trWidthArr[3] + 'rpx' }" v-else>
							{{ item.nameDishes }}
						</view>
						<view class="td" :style="{ width: trWidthArr[4] + 'rpx' }">
							{{ item.remarks ? item.remarks : '无' }}
						</view>
						<view class="td">{{ item.createTime_show }}</view>
					</view>
				</view>
			</view>
			<u-empty text="暂无订单数据" mode="page" v-if="orderList.length == 0"></u-empty>
		</view>
		<MyFooter :checkIndex="0"></MyFooter>
		<Bluetooth ref="Bluetooth" :show="showBluetooth" @hideBluetoothBox="hideBluetoothBox"
			@connectStatus="connectStatus"></Bluetooth>
		<u-popup v-model="showPrintSet" @click="showPrintSet = !showPrintSet" mode="right" length="85%">
			<PrintSet />
		</u-popup>
		<u-toast ref="uToast"></u-toast>

		<view class="merchantBox">
			<u-popup mode="bottom" v-model="showSelect" :closeable="true" @touchmove.stop.prevent="">
				<view class="merchantContent">
					<view class="title">请选择商户</view>
					<view class="merSchantContent">
						<input type="text" v-model="merchantName" placeholder="请输入店铺名称">
						<view class="" @click="_getStoreList('merchant')">搜索</view>
					</view>
					<view class="merList" v-for="(item, index) in merchantList" :key="index"
						@click="_getMerchantToekn(item.id)">
						{{ item.storeName }}
					</view>
				</view>
			</u-popup>
		</view>
		<u-modal v-model="warnVisible" title='提示' @confirm="toPrint" :show-cancel-button="true"
			:content='`请注意，您的门店截单时间为【${cutOffTime}】现在打印订单容易漏单，漏单扣一分扣20，请确认是否继续打印`'></u-modal>
	</view>
</template>

<script>
	import {
		getStoreSystemInfo,
		getStoreGoodList,
		exportExcelById,
		changeStoreState,
		getOrderWithCompany,
		getMenuListWithNum,
		getStoreToken,
		getMyInfo,
		getStoreList,
		getCompanyInfoById,
		setPrintData
	} from '@/utils/req/api.js';
	import MyFooter from '@/components/footer/footer.vue';
	import Bluetooth from '@/components/bluetooth/bluetooth.vue';
	import Print from '@/components/print/print.vue';
	import PrintSet from '@/components/print/printSet.vue';
	import mixinShareApp from '@/components/mixinShareApp/mixinShareApp.js';
	import {
		mapActions,
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex';
	import {
		formatDate
	} from '@/utils/commen.js'
	export default {
		components: {
			MyFooter,
			Bluetooth,
			Print,
			PrintSet
		},
		mixins: [mixinShareApp],
		data() {
			return {
				storeInfo: '',
				app: {},
				hcOrderDetailedInfo: {
					list: [],
					orderTotal: '',
				},
				statusMap: {
					"未接单": {
						status: '未接单',
						btnName: '请点击接单',
						clsName: 'error'
					},
					"出餐中": {
						status: '出餐中',
						btnName: '是否完成出餐',
						clsName: 'ing'
					},
					"已出餐": {
						// "已完成": {
						status: '已出餐',
						// status: '已完成',		// 等接口修改成已完成后再同步一致
						btnName: '已完成出餐',
						clsName: 'success'
					},
				},
				businessHours: [],
				businessHoursStr: '-',

				allChecked: false,
				checked: false,
				orderList: [],
				pageNo: 1,
				pageSize: -1,
				moreOrderFlag: false,
				checkedList: [],

				trWidthArr: [2, 2, 2, 2, 2],
				trWidthTotal: '',

				showBluetooth: false,
				showPrintSet: false,
				connectedPriter: false, // 是否连接蓝牙

				timeRangeChecked: false,
				rangeStart: {
					show: false,
					default: [0, 0],
					time: '19:00',
					list: [],
				},
				rangeEnd: {
					show: false,
					default: [0, 0],
					time: '20:00',
					list: [],
				},

				current: 0,

				myInfo: '', //商家信息
				isBigestAuth: false, //是否是最大权限
				showSelect: false, //商家选择弹窗的显隐
				merchantList: [], //商家列表
				merchantName: '', //商家列表

				timer: '', //按照营业结束时间倒计时刷次订单数据，防止漏单
				warnVisible: false,
				cutOffTime: ''
			};
		},

		// 分享到微信
		onShareAppMessage: function() {
			return this.shareApp();
		},
		// 分享到朋友圈
		onShareTimeline() {
			return this.shareApp();
		},

		created() {
			this.app = getApp();
			this.setTimeRangeList();
		},
		onLoad() {
			console.log('我是首页，onLoad');
		},
		onUnload() {
			console.log('首页，onUnload，清除定时刷新');
			clearInterval(this.timedRefresh);
		},
		onShow() {
			console.log('我是首页，onShow');
			this.getStoreSystemInfo().then(() => {
				this.getStoreGoodList();

				this.startRefreshTimer();
			});
			this.trWidthArr = [2, 2, 2, 2, 2];
			this.trWidthTotal = 0;
			this.allChecked = false;
			this.checkedList = [];

			this._getMyInfo('order');

			this.myInfo = uni.getStorageSync('myInfo');
			this.isBigestAuth = uni.getStorageSync('isBigestAuth');
			// this._getStoreList();
		},
		computed: {
			...mapState('commonModule', ['companyList']),
		},
		methods: {
			...mapActions('commonModule', ['_getMyInfo']),

			//展示切换商家端的弹窗
			showChangeMerchant() {
				this.showSelect = true;
			},
			//获取商户token
			async _getMerchantToekn(id) {
				let res = await getStoreToken({
					id
				});
				console.log('res', res);
				uni.setStorageSync('token', res.data.result.token);
				this._getMercantInfo();
			},
			//获取商户信息
			async _getMercantInfo() {
				let res = await getMyInfo();
				console.log('商户信息res', res);
				uni.setStorageSync('myInfo', res.data.result);
				uni.setStorageSync('isBigestAuth', true);
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},
			//获取商户列表
			async _getStoreList(type) {
				let params = {
					pageSize: -1,
					pageNumber: 1,
				}
				if (type == 'merchant') {
					params.storeName = this.merchantName
				}
				let res = await getStoreList(params);
				this.merchantList = res.data.result.records;
			},
			//回总权限的商户端
			goBack() {
				uni.setStorageSync('isBigestAuth', false);
				this._getMerchantToekn('1608912445638709250');
			},

			// 蓝牙状态
			connectStatus(val) {
				console.log('connectStatus：', val);
				this.connectedPriter = val;
			},
			//获取商家的相关信息
			async getStoreSystemInfo() {
				let res;
				if (this.current === 0) {
					res = await getStoreSystemInfo();
				} else {
					res = await getMenuListWithNum({
						merchantId: uni.getStorageSync('myInfo').id,
						companyId: uni.getStorageSync('companyId')
					});
				}

				if (this.current === 0) {
					this.storeInfo = res.data.result;
				}
				let total = 0;
				if (res.data.result.hcOrderDetailedList) {
					res.data.result.hcOrderDetailedList.forEach(item => {
						total = item.commodityQuantity + total;
					});
				}
				this.storeInfo.notExportedCount = res.data.result.notExportedCount;
				this.hcOrderDetailedInfo.orderTotal = total;
				this.hcOrderDetailedInfo.list = res.data.result.hcOrderDetailedList;

				this.storeInfo.hcOrderDetailedList.forEach(item => {
					total = item.commodityQuantity + total;
				});
				this.storeInfo.orderTotal = total;
				this.setBusinessHours();
			},
			// 营业时间数据
			setBusinessHours() {
				let hours = this.storeInfo.businessHours;
				hours = JSON.parse(hours);
				let str = '';
				let list = [];
				let endTimeList = [];
				hours.forEach(val => {
					if (val.startTime) {
						endTimeList.push(val.endTime);
						str += '，' + val.startTime + '-' + val.endTime;
						if (val.startTime > val.endTime) {
							list.push([val.startTime + ':00', '23:59:59']);
							list.push(['00:00:00', val.endTime + ':59']);
						} else {
							list.push([val.startTime + ':00', val.endTime + ':59']);
						}
					}
				})
				this.businessHoursStr = str.replace('，', '');
				this.businessHours = list;

				this.timedRefreshOrderData(endTimeList);
			},
			// 获取商家订单信息
			async getStoreGoodList(type) {
				let res;
				if (this.current === 0) {
					res = await getStoreGoodList({
						pageNo: 1,
						pageSize: this.pageNo * this.pageSize
					});
				} else {
					res = await getOrderWithCompany({
						pageNo: 1,
						pageSize: this.pageNo * this.pageSize,
						merchantId: uni.getStorageSync('myInfo').id,
						companyId: this.companyList[this.current].id
					});
				}

				this.orderList = [];
				var list = res.data.result.records;

				// 调试--
				/* var obj =	{
						supplyAddress: 'A15',
						pickingSerialNo: 18,
						nameTakingMeal: '张三',
						nameDishes: '好吃的小碗菜',
						remarks: '11',
						hcOrderDetailedList: [
							{commodityQuantity: 1, tradeName: '好吃的小碗菜'},
							{commodityQuantity: 2, tradeName: '白米饭'},
							{commodityQuantity: 1, tradeName: '青菜'},
						],
						createTime: '2023-08-26 08:00:56'
					}
				var aa
				aa = Object.assign({}, obj);list.push(aa);aa.createTime = '2023-08-26 22:03:04';aa.pickingSerialNo++;
				aa = Object.assign({}, obj);list.push(aa);aa.createTime = '2023-08-27 08:35:56';aa.pickingSerialNo+=2;
				aa = Object.assign({}, obj);list.push(aa);aa.createTime = '2023-08-26 16:01:06';aa.pickingSerialNo+=3; */
				// 调试--


				this.trWidthArr = [2, 2, 2, 2, 2];
				var orderList = [];
				var isStore_H = this.storeInfo && this.storeInfo.storeName && this.storeInfo.storeName.endsWith(
					'（H）'); // 特殊商家不拆单
				list.forEach(item => {
					item.checked = false;
					item.createTime_show = item.createTime.split(' ')[1];
					if (item.supplyAddress && item.supplyAddress.length > this.trWidthArr[0]) {
						this.trWidthArr[0] = item.supplyAddress.length;
					}
					if (item.pickingSerialNo && item.pickingSerialNo.length > this.trWidthArr[1]) {
						this.trWidthArr[1] = item.pickingSerialNo.length;
					}
					if (item.nameTakingMeal && item.nameTakingMeal.length > this.trWidthArr[2]) {
						this.trWidthArr[2] = item.nameTakingMeal.length;
					}
					if (item.remarks.length > this.trWidthArr[4]) {
						this.trWidthArr[4] = item.remarks.length;
					}

					var _num = ' x1';
					var nameDishes = item.nameDishes;
					let nameDishesLength = item.nameDishes.length;

					if (isStore_H) {
						// 自选餐厅，单子不拆开
						let nameDishes = '';
						if (item.hcOrderDetailedList && item.hcOrderDetailedList.length) {
							let redFontIndexs = [];
							item.hcOrderDetailedList.forEach((cItem, cIndex) => {
								let specifications = cItem.specifications ?
									`(${cItem.specifications})` : '';
								nameDishes +=
									`+${cItem.tradeName}${specifications} x${cItem.commodityQuantity}`;
								if (cItem.commodityQuantity > 1) {
									redFontIndexs.push(cIndex);
								}
							})
							item.nameDishes = nameDishes.replace('+', '');
							// 数量大于2时，显示红色
							if (redFontIndexs.length) {
								item.nameDishes_red = {
									indexs: redFontIndexs,
									list: item.nameDishes.split('+')
								};
							}
						}
						// item.nameDishes += _num;
						nameDishesLength = Math.max(item.nameDishes.length, nameDishesLength);
						orderList.push(item);

					} else {
						// 其余餐厅单子拆开显示、打印
						if (item.hcOrderDetailedList && item.hcOrderDetailedList.length) {
							item.hcOrderDetailedList.forEach((cItem, cIndex) => {
								let quantity = cItem.commodityQuantity
								let specifications = cItem.specifications ?
									`(${cItem.specifications})` : '';

								while (quantity > 0) {
									item.multipleOrders = true;
									let copyItem = Object.assign({}, item);
									copyItem.hcOrderDetailedList = 'isCopyItem'
									copyItem.id = cItem.id;
									copyItem.nameDishes = cItem.tradeName ? cItem.tradeName +
										specifications + _num : '未知';
									nameDishesLength = Math.max(copyItem.nameDishes.length,
										nameDishesLength)
									orderList.push(copyItem);
									quantity--;
								}

							})
						}


					}


					// 子项的名称不确定，所以该列在最后判断
					if (nameDishesLength > this.trWidthArr[3]) {
						this.trWidthArr[3] = nameDishesLength;
					}

				});
				console.log(orderList);
				this.orderList = orderList;

				let trWidthTotal = 0;
				this.trWidthArr.forEach((item, index) => {
					this.$set(this.trWidthArr, index, item * 28 + 50);
					trWidthTotal = trWidthTotal + (item * 28 + 50) + 20;
				});
				this.trWidthTotal = trWidthTotal + 200;

				this.sortOrderList(); // 订单排序
				this.updateCheckedOrder();
				
				if(type=='print'){
					this.doCheckOverTime();
				}
			},

			// 全选
			changeAllCheck() {
				this.allChecked = !this.allChecked;
				if (this.allChecked) {
					this.timeRangeChecked = false;
				}
				this.orderList.forEach(item => {
					item.checked = this.allChecked;
				});
			},
			// 单选
			changeRadioState(index) {
				console.log(6666);
				let obj = JSON.parse(JSON.stringify(this.orderList[index]));
				obj.checked = !obj.checked;
				this.$set(this.orderList, index, obj);

				/* if (checkedList.length == this.orderList.length) {
					this.allChecked = true;
				} */
			},

			//开始到截单时自动刷新订单的倒计时
			async startRefreshTimer() {
				clearTimeout(this.timer);
				let year = new Date().getFullYear();
				let month = new Date().getMonth() + 1;
				let day = new Date().getDate();
				let nowTimeStamp = new Date().getTime();
				let endTimeStamp;
				if (this.current == 0) {
					let tempTime = JSON.parse(this.storeInfo.businessHours)[0];
					this.cutOffTime = tempTime.endTime;
					endTimeStamp = new Date(`${year}-${month}-${day} ${tempTime.endTime}:00`).getTime();
				} else {
					let copanyInfoRes = await getCompanyInfoById({
						id: uni.getStorageSync('companyId')
					});
					let copanyInfo = copanyInfoRes.data.result;
					this.cutOffTime = copanyInfoRes.data.result.endTime;
					endTimeStamp = new Date(`${year}-${month}-${day} ${copanyInfoRes.data.result.endTime}:00`)
						.getTime();
				}
				console.log('endTimeStamp - nowTimeStamp', endTimeStamp - nowTimeStamp);
				this.timer = setTimeout(() => {
					this.getStoreGoodList();
				}, endTimeStamp - nowTimeStamp)
			},
			checkOverTime() {
				let flag = false;
				for (let i = 0; i < this.orderList.length; i++) {
					if (this.orderList[i].checked) {
						flag = true;
						break;
					}
				}
				if(flag){
					this.doCheckOverTime();
				}else{
					this.getStoreGoodList('print');
				}
			},
			async doCheckOverTime(){
				//打印时等订单获取完成之后再进行打印
				let year = new Date().getFullYear();
				let month = new Date().getMonth() + 1; 
				let day = new Date().getDate();
				let nowTimeStamp = new Date().getTime();
				let endTimeStamp;
				if (this.current == 0) {
					let tempTime = JSON.parse(this.storeInfo.businessHours)[0];
					endTimeStamp = new Date(`${year}-${month}-${day} ${tempTime.endTime}:00`).getTime();
				} else {
					let copanyInfoRes = await getCompanyInfoById({
						id: uni.getStorageSync('companyId')
					});
					let copanyInfo = copanyInfoRes.data.result;
					endTimeStamp = new Date(`${year}-${month}-${day} ${copanyInfoRes.data.result.endTime}:00`)
						.getTime();
				}
				if (nowTimeStamp < endTimeStamp) {
					this.warnVisible = true;
				} else {
					this.$refs.print.clickPrintBtn();
				}
			},
			toPrint() {
				this.$refs.print.clickPrintBtn();
			},
			// 给打印\导出获取选中的订单
			getCheckedList(callback) {
				let flag = false;
				for (let i = 0; i < this.orderList.length; i++) {
					if (this.orderList[i].checked) {
						flag = true;
						break;
					}
				}
				if (!flag) {
					//如果没有选中的则默认全选
					this.checkedList = this.orderList;
					callback && callback(this.checkedList);
				} else {
					//如果有选中的则打印选中的
					let checkedList = [];
					this.orderList.forEach(item => {
						if (item.checked) {
							checkedList.push(item);
						}
					});
					this.checkedList = checkedList;
					callback && callback(this.checkedList);
				}
			},

			//导出
			async handleExportXls() {
				this.getCheckedList();
				if (this.current === 0) {
					var ids = this.checkedList.map(val => val.id);
					uni.navigateTo({
						url: '/pages/export/export?ids=' + ids.join(',') + '&token=' + uni.getStorageSync(
							'token') + '&storeName=' + this.storeInfo.storeName
					});
				} else {
					var ids = this.checkedList.map(val => val.id);
					uni.navigateTo({
						url: `/pages/export/companyExport?ids=${ids.join(',')}&token=${uni.getStorageSync('token')}&storeName=${this.storeInfo.storeName}&companyId=${this.companyList[this.current].id}`
					});
				}
			},
			async changeStoreState(type) {
				if (this.storeInfo.storeStatus == '已出餐') {
					return;
				}

				if (this.checkBusinessHours()) {
					let msg = '您的店铺营业时间是' + this.businessHoursStr + "，请在停止接单后，再点击接单！"
					this.$refs.uToast.show({
						title: msg,
						icon: false,
						duration: 5000,
					})
					return;
				}

				let obj = {
					storeStatus: type == 'accept' ? '出餐中' : '已出餐'
				};

				if (this.storeInfo.storeStatus == '未接单') {
					obj.storeStatus = '出餐中'
				} else if (this.storeInfo.storeStatus == '出餐中') {
					// obj.storeStatus = '已完成'
					obj.storeStatus = '已出餐'
				} else {
					return;
				}

				let res = await changeStoreState(obj);
				if (res.data.success) {
					this.storeInfo.storeStatus = res.data.result.storeStatus;
				} else {
					this.$showToast.call(this, res.data.message, 'warning');
				}
			},

			// 校验当前时间是否在营业时间段内
			checkBusinessHours() {
				let isInBusinessHours = false; // 在营业时间外的，不可以接单
				let nowTime = formatDate(new Date(), 'hh:mm:ss')

				this.businessHours.forEach(val => {
					if (nowTime >= val[0] && nowTime <= val[1]) {
						isInBusinessHours = true;
					}
				})
				return isInBusinessHours;
			},

			// 打开蓝牙面板
			showBluetoothBox() {
				this.showBluetooth = true;
			},
			//  打开打印设置面板
			showPrintSetBox() {
				this.showPrintSet = true;
			},

			// 关闭蓝牙面板
			hideBluetoothBox() {
				this.showBluetooth = false;
			},

			//跳转公用函数
			goToPage(type) {
				let url;
				switch (type) {
					case 'store':
						url = '/pages/index/index';
						break;
					case 'afterSales':
						url = '/pages/index/afterOrder';
						break;
				}
				uni.reLaunch({
					url
				});
			},
			//二期需求
			tabsChange(e) {
				console.log('e', e);
				this.current = e;
				if (this.current !== 0) {
					uni.setStorageSync('companyId', this.companyList[this.current].id);
				}
				this.getStoreGoodList();
				this.getStoreSystemInfo();

				this.startRefreshTimer();
			},
			//二期需求

			// 点击订单时间，按时间排序订单
			changeSortBy(type) {
				let oldType = this.app.globalData.orderSortType;
				this.app.globalData.orderSortType = type;
				if (oldType != type) {
					this.getStoreGoodList();
				}
			},
			// 订单排序
			sortOrderList() {
				if (this.app.globalData.orderSortType == 'createTime') {
					this.orderList.sort((a, b) => {
						return new Date(b.createTime) - new Date(a.createTime)
					})
				}
				/* if (this.app.globalData.orderSortType == 'default') {
					// 如果要这个功能，需考虑nameDishes_red数据
					this.orderList.sort((a, b) => {
						return a.nameDishes.localeCompare(b.nameDishes, 'zh-CN');
					})
				} */
			},

			// 区间打印下拉选项
			setTimeRangeList() {
				let i = 0;
				let hourList = [];
				while (i < 24) {
					let hour = 19 + i;
					hour = hour >= 24 ? hour - 24 : hour;
					hour = hour < 10 ? '0' + hour : '' + hour;
					hourList.push({
						label: hour + '时',
						value: hour,
					})
					i++;
				}

				let j = 0;
				let minList = [];
				while (j < 60) {
					let min = j < 10 ? '0' + j : '' + j;
					minList.push({
						label: min + '分',
						value: min,
					})
					j++
				}
				let opt = [hourList, minList];
				this.rangeStart.list = [hourList, minList];
				this.rangeEnd.list = [hourList, minList];
				// console.log(JSON.parse(JSON.stringify(opt)));
			},

			// 确定区间的开始时间
			confirmStartTime(list) {
				this.rangeStart.time = list[0].value + ':' + list[1].value
				let options = this.rangeStart.list;
				let index1 = options[0].findIndex(val => val.value == list[0].value)
				let index2 = options[1].findIndex(val => val.value == list[1].value)
				this.rangeStart.default = [index1, index2];
				console.log([index1, index2]);

				this.rangeEnd.list[0] = this.rangeStart.list[0].filter((val, idx) => idx > index1)
				if (list[0].value == '18') {
					this.rangeEnd.list[0] = [{
						value: '18',
						label: '18时'
					}]
					this.rangeEnd.list[1] = this.rangeStart.list[1].filter((val, idx) => idx >= index2)
				} else {
					this.rangeEnd.list[1] = this.rangeStart.list[1]
				}

				this.rangeStart.show = false;
				this.rangeEnd.show = true;
			},

			// 返回上一步
			backToStart() {
				let list = this.rangeEnd.list;
				this.rangeEnd.time = list[0][0].value + ':' + list[1][0].value
				this.rangeEnd.show = false;
				this.rangeStart.show = true;
			},

			// 确定区间的截止时间
			confirmEndTime(list) {
				this.rangeEnd.time = list[0].value + ':' + list[1].value
				let options = this.rangeEnd.list;
				let index1 = options[0].findIndex(val => val.value == list[0].value)
				let index2 = options[1].findIndex(val => val.value == list[1].value)
				this.rangeEnd.default = [index1, index2];
				this.timeRangeChecked = true;
				this.checkByTimeRange();
			},

			// 刷新列表时根据勾选选给定勾选的订单
			updateCheckedOrder() {
				if (this.allChecked) {
					this.orderList.forEach(item => {
						item.checked = true;
					});
				}
				if (this.timeRangeChecked) {
					this.checkByTimeRange();
				}
			},

			// 根据时间段勾选
			checkByTimeRange(uncheck = false) {
				let startTime = this.rangeStart.time + ':00';
				let endTime = this.rangeEnd.time + ':59';

				let day1 = new Date();
				let day2 = new Date();
				let nowTime = formatDate(new Date(), 'hh:mm:ss')


				if (nowTime >= '19:00:00' && nowTime <= '23:59:59') {
					day2.setDate(day2.getDate() + 1)
				} else {
					day1.setDate(day1.getDate() - 1)
				}

				let _day1 = `${day1.getFullYear()}-${day1.getMonth() + 1}-${day1.getDate()}`;
				let _day2 = `${day2.getFullYear()}-${day2.getMonth() + 1}-${day2.getDate()}`;
				if (startTime >= '19:00:00' && startTime <= '23:59:59') {
					startTime = new Date(`${_day1} ${startTime}`)
				} else {
					startTime = new Date(`${_day2} ${startTime}`)
				}
				if (endTime >= '19:00:00' && endTime <= '23:59:59') {
					endTime = new Date(`${_day1} ${endTime}`)
				} else {
					endTime = new Date(`${_day2} ${endTime}`)
				}

				console.log(startTime, endTime)

				let trueList = [];
				let falseList = [];
				this.orderList.forEach(val => {
					let orderTime = new Date(val.createTime);
					let isInRangeTime = orderTime >= startTime && orderTime <= endTime;

					if (uncheck) { // 取消勾选
						if (isInRangeTime) {
							val.checked = false;
						}
					} else { // 勾选上
						if (isInRangeTime) {
							val.checked = true;
							trueList.push(val);
						} else {
							val.checked = false;
							falseList.push(val);
						}
					}
				})
				this.orderList = [].concat(trueList, falseList)

			},

			// 切换选中区间
			clickTimeRangeChecked() {
				this.timeRangeChecked = !this.timeRangeChecked;
				if (this.timeRangeChecked) {
					this.checkByTimeRange();
					this.allChecked = false;
				} else {
					this.checkByTimeRange(true);
				}
			},

			// 定时监测来刷新订单列表
			timedRefreshOrderData(endTimeList) {
				let _this = this;
				if (this.timedRefresh) {
					return;
				}

				this.timedRefresh = setInterval(() => {
					let inBusiness = this.checkBusinessHours();
					if (this.lastRefresh && !inBusiness) {
						_this.getStoreGoodList();
						console.log('此时停止营业，刷新一次列表');
					}
					console.log('定时检查是否在营业时间内：', inBusiness);
					this.lastRefresh = inBusiness;
				}, 5000)

				/* this.timedRefresh = setInterval(() => {
					let nowTime = formatDate(new Date(), 'hh:mm:ss');
					let lastTime = _this.lastRecordTime
					endTimeList.forEach(val => {
						let endTime = val + ':00';
						if (lastTime && lastTime <= endTime && endTime < nowTime) {
							_this.getStoreGoodList();
							console.log('停止营业，刷新一次列表');
						} 
					})
					_this.lastRecordTime = nowTime;
				}, 5000) */
			},
			async _setPrintData() {
				console.log('正在上传打印记录')
				let params = {
					merchantId: this.myInfo.id,
					merchantName: this.myInfo.storeName,
					type: this.current === 0 ? 0 : 1,
				}
				if (this.current !== 0) {
					let companyId = uni.getStorageSync('companyId');
					let companyInfo = this.companyList.filter(item => item.id == companyId)[0];
					console.log('companyInfo', companyInfo.companyShortName);
					params.companyId = companyId;
					params.companyName = companyInfo.companyShortName;

				}
				console.log('params', params);
				let res = await setPrintData(params);
				console.log('res', res);
			}
		},
		onReachBottom() {
			if (!this.moreOrderFlag) {
				if (this.orderList.length != 0 && this.orderList.length % this.pageSize == 0) {
					this.pageNo = this.pageNo + 1;
					this.moreOrderFlag = true;
					this.getStoreGoodList();
					setTimeout(() => {
						this.moreOrderFlag = false;
					}, 1000);
				}
			}
		}
	};
</script>


<style lang="scss" scoped>
	$success-color: #70B603;
	$red-color: #f32d4a;

	.storeBox {
		background-color: #f5f5f5;
		padding-bottom: 150rpx;
		min-height: 100vh;
	}

	.topMenu {
		background-color: #fff;
		padding: 20rpx;
		@include flexs(flex-start, flex-start);

		.tit-txt {
			margin-right: 30rpx;
			font-size: 40rpx;
			line-height: 56rpx;
			color: rgba(0, 0, 0, 0.35);

			>view:nth-child(2) {
				width: 40rpx;
				height: 8rpx;
				background: #f1b825;
				margin: 0 auto;
				margin-top: 10rpx;
				display: none;
			}
		}

		.bluetooth {
			flex: 1;
			display: flex;
			justify-content: flex-end;
			margin-right: 0px !important;

			>view {
				background-color: $red-color;
				border-radius: 4rpx;
				padding: 14rpx 28rpx;
				font-size: 26rpx;
				color: #fff;
			}

			.changeMerchant {
				margin-right: 10rpx;
			}

			.is-connected {
				background-color: $success-color;
			}

			.print-set {
				background-color: #5cacf2;
				margin-right: 4rpx;
			}
		}

		>.check {
			color: #000;

			>view:nth-child(2) {
				display: block;
			}
		}
	}

	.tabsContent {
		padding: 10rpx 20rpx;
		background-color: #fff;

		/deep/.u-tabs {
			.u-tab-item {
				margin-left: 30rpx !important;

				&:nth-child(1) {
					margin-left: 0 !important;
				}
			}
		}
	}

	.warn {
		background-color: #f6e2d4;
		color: #fa690a;
		font-size: 28rpx;
		line-height: 2;
		padding: 10rpx 60rpx;
	}

	.notice {
		@include flexs(flex-start, flex-start);
		padding: 40rpx;
		background-color: #fff;
		color: rgba(0, 0, 0, 0.55);

		>view {
			font-size: 28rpx;
			line-height: 1.5;
		}

		image {
			width: 40rpx;
			height: 40rpx;
			flex-shrink: 0;
			margin-right: 20rpx;
		}
	}

	.menuContent {
		padding: 40rpx;
		background-color: #fff;
		margin-top: 20rpx;

		>view {
			@include flexs(space-between, center);
			font-size: 30rpx;
			line-height: 1.5;
			margin-bottom: 20rpx;
			background-color: #f5f5f5;
			padding: 15rpx 20rpx;

			>view:nth-child(1) {
				max-width: 80%;
				display: -webkit-box;
				overflow: hidden;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
			}
		}

		>.menuTop {
			// color: rgba(0, 0, 0, 0.55);
			font-weight: bold;
			color: #000;
		}

		.total {
			@include flexs(flex-end, center);
			background-color: #fff;
			padding-right: 0;
			color: rgba(0, 0, 0, 0.55);

			text {
				color: #000;
				margin-left: 10rpx;
			}
		}
	}

	.storeState {
		padding: 40rpx;
		background-color: #fff;
		margin-top: 20rpx;

		.title {
			font-size: 30rpx;
			line-height: 2;
			font-weight: bold;

			text {
				margin-left: 10rpx;
				font-weight: 100;
			}

			.error {
				color: $red-color;
				font-weight: bold;
			}

			.ing {
				color: #6abceb;
				font-weight: bold;
			}

			.success {
				color: $success-color;
				font-weight: bold;
			}
		}

		.tit-new {
			font-size: 32rpx;
			line-height: 2;
			display: flex;
			justify-content: space-between;

			.cczz {
				font-size: 40rpx;
				padding-top: 12rpx;
			}

			.t-btn {
				flex: 1;
				margin-left: 30rpx;
			}

			.status {
				width: 100%;
				padding: 18rpx 0rpx;
				color: #fff;
				font-weight: bold;
				letter-spacing: 0.5rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.error {
				background-color: $red-color;
			}

			.ing {
				background-color: #fa850c;
			}

			.success {
				background-color: $success-color;
			}
		}

		.state {
			@include flexs(space-between, center);
			margin-top: 32rpx;

			>view {
				width: 45%;
				background-color: $success-color;
				// background-color: #fa690a;
				color: #fff;
				text-align: center;
				font-size: 27rpx;
				line-height: 2;
				padding: 5rpx 0;
				position: relative;

				.num {
					position: absolute;
					right: -10rpx;
					top: -10rpx;
					width: 30rpx;
					height: 30rpx;
					border-radius: 50%;
					background-color: #fd2a2a;
					font-size: 24rpx;
					line-height: 30rpx;
					color: #fff;
					text-align: center;
				}
			}

			view:nth-child(2) {
				margin-left: 26rpx;
			}
		}
	}

	.orderContent {
		margin-top: 20rpx;
		width: 100%;
		background-color: #fff;

		/deep/ {
			.u-empty {
				padding: 80rpx 0;
				background-color: #fff;
				width: calc(100% - 40rpx);
				margin: 0 auto;
				border-radius: 10rpx;
				min-height: 30vh;
			}
		}

		.or-cb {
			transform: scale(0.7);
		}

		.buttonBox {
			display: flex;
			font-size: 28rpx;
			line-height: 2;
			background-color: #fff;
			border-bottom: 1px solid #eee;
			padding: 10rpx 40rpx;

			.time-range {
				display: flex;

				.cur-time-val {
					border: 1px solid #c0bbbb;
					padding: 0px 4px;
				}
			}
		}

		.allCheck {
			display: flex;
			margin-right: 50rpx;

			uni-checkbox {
				margin-right: 10rpx;
			}
		}

		.tableBox {
			overflow: hidden;
			overflow-x: scroll;
			background-color: #fff;
			padding: 20rpx 0;
		}

		.table {
			background-color: #fff;
			padding: 20rpx;
			display: flex;
			flex-direction: column;

			scroll-view {
				width: 1000px !important;
			}

			.tr {
				display: flex;
				border: 1px solid #eee;
				border-bottom: 0;
				color: #000;
				max-height: 150rpx;

				&.multipleOrders {
					// color: #f79c9c;
				}

				&:nth-child(1) {
					background-color: #eee;
					border: 0;

					.td {
						color: #000;
					}
				}

				&:last-child {
					border-bottom: 1px solid #ccc;
				}

				.td {
					padding: 10rpx;
					font-size: 28rpx;
					width: 100rpx;
					text-align: center;
					flex-shrink: 0;
					line-height: 1.5;

					&:first-child {
						width: 50rpx;
					}

					&:last-child {
						// width: 360rpx
					}

					&:nth-child(5) {
						text-align: left;
					}

					.error {
						color: red;
						font-weight: bold;
						font-size: 32rpx;
					}

					&:last-child {
						width: 200rpx;
					}

					&.sort-col {
						font-weight: bold;
					}

					&.isSort {
						color: red;
					}
				}

			}
		}

		.orderList {
			@include flexs(flex-start, flex-start);
			font-size: 28rpx;
			line-height: 2;
			margin-bottom: 20rpx;
			background-color: #fff;
			padding: 40rpx;

			uni-checkbox {
				margin-right: 10rpx;
			}

			>view {
				@include flexs(flex-start, flex-start);
				flex-direction: column;
				width: 100%;
				flex-wrap: wrap;

				>view {
					width: 100%;
					@include flexs();
					flex-wrap: wrap;
					// color: rgba(0, 0, 0, 0.55);
					color: #000;

					text {
						color: #000;
						margin: 0 20rpx;
					}
				}

				>.foods {
					@include flexs(flex-start, flex-start);
					line-height: 1.5;

					>.det {
						flex: 1;
						margin-left: 20rpx;

						text {
							margin-left: 0;
							margin-right: 4rpx;
							line-height: 1.5;
						}

						.error {
							color: red;
							font-weight: bold;
							font-size: 32rpx;
						}
					}
				}

				>.w30 {
					>view {
						width: calc(100% / 3);
					}
				}

				>.w10 {
					@include flexs(flex-start, flex-start);

					>view:nth-child(2) {
						@include flexs();
						flex-wrap: wrap;

						>view {
							width: 50%;
							color: #000;
							padding-left: 10rpx;
						}
					}
				}

				>.w50 {
					.note {
						font-size: 32rpx;
						line-height: 2;
					}

					>view {
						// width: 50%;
					}
				}
			}
		}
	}

	.merchantContent {
		.title {
			font-size: 32rpx;
			line-height: 2;
			font-weight: bold;
			text-align: center;
			margin-bottom: 14rpx;
		}

		.merSchantContent {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 30rpx;
			padding: 24rpx 0;

			input {
				background-color: rgba(0, 0, 0, 0.05);
				border-radius: 10rpx;
				flex: 1;
				padding: 10rpx 24rpx;
				font-size: 30rpx;
				line-height: 2;
				box-sizing: content-box;
			}

			view {
				background-color: #f1b825;
				padding: 0 10rpx;
				line-height: 2;
				border-radius: 10rpx;
				color: #fff;
			}

			view {
				margin-left: 20rpx;
			}
		}

		.merList {
			border-bottom: 1px solid rgba(0, 0, 0, 0.05);
			font-size: 28rpx;
			line-height: 40rpx;
			padding: 24rpx 0;

			&:last-child {
				border-bottom: 0;
			}
		}
	}
</style>
<style lang="scss">
	.storeBox {
		/deep/.uni-checkbox-input {
			border-radius: 50%;
			width: 35rpx;
			height: 35rpx;
			// border-color: #FA690A !important;
		}

		/deep/.uni-checkbox-input-checked {
			color: #fa690a !important;
			border: 1px solid #fa690a !important;
		}
	}

	.merchantBox {
		/deep/.u-drawer-bottom {
			width: 100% !important;
			padding: 36rpx 20rpx 40rpx 20rpx;
			border-top-left-radius: 40rpx;
			border-top-right-radius: 40rpx;
			min-height: 70vh !important;
			max-height: 70vh;
			padding-bottom: 100rpx !important;
			overflow-y: auto !important;
		}

		/deep/ {
			.u-drawer__scroll-view {
				max-height: 70vh;
			}
		}
	}
</style>